<template>
  <el-form
    v-show="getShow"
    ref="formLogin"
    :model="loginData.loginForm"
    :rules="LoginRules"
    class="login-form"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <el-row class="mx-[-10px]">
      <el-col :span="24" class="px-10px">
        <el-form-item>
          <LoginFormTitle class="w-full" />
        </el-form-item>
      </el-col>

      <el-col :span="24" class="px-10px">
        <el-form-item prop="username">
          <el-input
            v-model="loginData.loginForm.username"
            :placeholder="t('login.mobileNumberPlaceholder')"
            :prefix-icon="iconMobile"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item prop="password">
          <el-input
            v-model="loginData.loginForm.password"
            :placeholder="t('login.passwordPlaceholder')"
            :prefix-icon="iconLock"
            show-password
            type="password"
            @keyup.enter="handleDirectLogin()"
          />
        </el-form-item>
      </el-col>
      <el-col
        :span="24"
        class="px-10px mt-[-20px] mb-[-20px]"
      >
        <el-form-item>
          <el-row justify="space-between" style="width: 100%">
            <el-col :span="6">
              <el-checkbox v-model="loginData.loginForm.rememberMe">
                {{ t('login.remember') }}
              </el-checkbox>
            </el-col>
            <el-col :offset="6" :span="12">
              <el-link
                class="float-right"
                type="primary"
                @click="setLoginState(LoginStateEnum.RESET_PASSWORD)"
              >
                {{ t('login.forgetPassword') }}
              </el-link>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="24" class="px-10px">
        <el-form-item>
          <XButton
            :loading="loginLoading"
            :title="t('login.login')"
            class="w-full"
            type="primary"
            @click="handleDirectLogin()"
          />
        </el-form-item>
      </el-col>
      <Verify
        v-if="loginData.captchaEnable === 'true'"
        ref="verify"
        :captchaType="captchaType"
        :imgSize="{ width: '400px', height: '200px' }"
        mode="pop"
        @success="handleLogin"
      />

    </el-row>
  </el-form>
</template>
<script lang="ts" setup>
import { ElLoading, ElMessage } from 'element-plus'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { Verify } from '@/components/Verifition'

import { useIcon } from '@/hooks/web/useIcon'

import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'

defineOptions({ name: 'LoginForm' })

const { t } = useI18n()
const message = useMessage()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconMobile = useIcon({ icon: 'ep:iphone' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { setLoginState, getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const LoginRules = {
  username: [required],
  password: [required]
}
const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    rememberMe: true // 默认记录我。如果不需要，可手动修改
  }
})



// 直接登录处理
const handleDirectLogin = async () => {
  // 防止重复点击
  if (loginLoading.value) {
    return
  }
  
  // 表单验证
  const data = await validForm()
  if (!data) {
    return
  }
  
  // 预先设置租户ID
  if (loginData.tenantEnable === 'true') {
    await getTenantId()
    const tenantId = authUtil.getTenantId()
    if (!tenantId) {
      ElMessage.error('租户信息未设置，请刷新页面重试')
      return
    }
  }
  
  // 根据验证码开关决定登录方式
  if (loginData.captchaEnable === 'false') {
    // 未开启验证码，直接登录
    await handleLogin({})
  } else {
    // 开启验证码，弹出验证码
    verify.value.show()
  }
}

// 获取验证码（保留原函数供验证码组件使用）
const getCode = async () => {
  // 防止重复点击
  if (loginLoading.value) {
    return
  }
  
  // 添加表单验证
  const data = await validForm()
  if (!data) {
    return
  }
  
  // 弹出验证码
  verify.value.show()
}
// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    // 从URL参数中获取租户编号
    let tenantId = currentRoute.value.params.tenantId

    // 备用方案1：从redirect参数中解析租户ID
    if (!tenantId && currentRoute.value.query.redirect) {
      const redirectMatch = currentRoute.value.query.redirect.toString().match(/\/login\/(\d+)/)
      if (redirectMatch) {
        tenantId = redirectMatch[1]
      }
    }

    // 备用方案2：直接从URL路径中解析
    if (!tenantId) {
      const pathMatch = window.location.pathname.match(/\/login\/(\d+)/)
      if (pathMatch) {
        tenantId = pathMatch[1]
      }
    }

    // 备用方案3：从完整URL中解析
    if (!tenantId) {
      const urlMatch = window.location.href.match(/\/login\/(\d+)/)
      if (urlMatch) {
        tenantId = urlMatch[1]
      }
    }

    if (tenantId) {
      // 设置租户ID
      authUtil.setTenantId(Number(tenantId))
    } else {
      // 如果URL中没有租户编号，尝试通过域名获取
      await getTenantByWebsite()
    }
  }
}
// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe
    }
  }
}
// 根据域名，获得租户信息
const getTenantByWebsite = async () => {
  if (loginData.tenantEnable === 'true') {
    const website = location.host
    const res = await LoginApi.getTenantByWebsite(website)
    if (res) {
      authUtil.setTenantId(res.id)
    }
  }
}
const loading = ref() // ElLoading.service 返回的实例
// 登录
const handleLogin = async (params: any) => {
  if (loginLoading.value) {
    return
  }
  
  loginLoading.value = true
  try {
    // 构建登录数据
    const loginDataLoginForm = { ...loginData.loginForm }
    loginDataLoginForm.captchaVerification = params.captchaVerification
    
    const res = await LoginApi.login(loginDataLoginForm)
    if (!res) {
      ElMessage.error('登录失败，请检查用户名和密码')
      return
    }
    
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    if (loginDataLoginForm.rememberMe) {
      const loginFormData = {
        ...loginDataLoginForm,
        tenantName: '' // 添加缺少的字段
      }
      authUtil.setLoginForm(loginFormData)
    } else {
      authUtil.removeLoginForm()
    }
    
    authUtil.setToken(res)
    
    if (!redirect.value) {
      redirect.value = '/'
    }
    
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      await push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请重试')
  } finally {
    loginLoading.value = false
    if (loading.value) {
      loading.value.close()
    }
  }
}


watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
onMounted(async () => {
  getLoginFormCache()
  await getTenantId()
})
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.login-code {
  float: right;
  width: 100%;
  height: 38px;

  img {
    width: 100%;
    height: auto;
    max-width: 100px;
    vertical-align: middle;
    cursor: pointer;
  }
}
</style>
